package com.xky.redis.controller;

import com.xky.redis.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author keying.xia
 * @date 2017/11/30
 */
@RestController
@RequestMapping(value = "/cache")
public class UserController {

    public static final Map<Integer,User> map = Collections.synchronizedMap(new HashMap<>());

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping(value = "/add")
    @CachePut(value = "#p0")
    public void add(){
        logger.info("更新...");
        User user = new User();
        user.setRedisKey("aaa");
        user.setAge(11);
        user.setPhone(1111L);
        user.setName("xky");
        user.setId(1);
        map.put(user.getId(),user);
    }


    @GetMapping(value = "/delete/{id}")
    @CacheEvict(value = "#p0",allEntries = true)
    public void delete(@PathVariable Integer id){
        logger.info("删除");
        if(map.containsKey(id)){
            map.remove(id);
        }
    }

    @GetMapping(value = "/update/{id}")
    @CachePut(value = "#p0")
    public void update(@PathVariable Integer id){
        logger.info("更新");
        if (map.containsKey(id)){
            User user = map.get(id);
            user.setName("lpp");
            map.put(user.getId(),user);
        }
    }


    @GetMapping(value = "/get/{id}")
    @Cacheable(value = "#p0")
    public User get(@PathVariable Integer id){
        logger.info("更新");
        if (map.containsKey(id)){
            return map.get(id);
        }
        return null;
    }


}
